#########################################################
## WD já setado via abertura do projeto
setwd("~/R/explorar")
## zera todos os objetos
rm(list = ls()) 

# modificações feitas neste script são localizadas com 
#  a pesquisa do texto "explorar:"

#######################################################
# reinstalação de pacotes QCA - feita em 27mar2025
# do script do Patrick Mello
#install.packages("QCA")
#install.packages("SetMethods")
#install.packages("readxl")
library("QCA")
library("SetMethods")
# do script do Adrian na disciplina
library(dplyr) # data transformation
library(tibble) # column to rownames
library(devtools) # session info and parameters
library(formattable) # nicer truth tables
# para ler arquivos xls
library(readxl)
# para gravar arquivos xls (com limitações)
library(writexl)

#################################################################
########################### funções pré-programadas
#################################################################
#### nome.funcao <- function(parm.funcao)
####   {  #begin function
#### comandos da funcao  
#### return (resultado.funcao) 
####  fim da função
####   }  #endfunction


###  procedure section (lembrança do cobol)

###################################################################################
########################
###########                   preparação geral dos dados provenientes do V-Dem (todos)
########################
###################################################################################


############################################################################################
# carrega toda a base
############################################################################################

modelo.VDem = readRDS("V-Dem-CY-Full+Others-v12.rds")
# filtra por países
#  aqui já foram retirados GT e NI
modelo.VDem.por.pais = modelo.VDem [modelo.VDem$country_text_id %in% 
                                      c ("ARG", "BOL", "BRA", "CHL", "COL", "CRI", "DOM", "SLV",
                                         "HND", "MEX", "PAN", "PRY", "PER", "URY", "VEN"), ]
# filtra por ano
#  inicio e fim deixados com uma folga de um ano
data.inicio = 1977
data.fim = 2025

modelo.VDem.por.pais.data = modelo.VDem.por.pais [((modelo.VDem.por.pais$year > (data.inicio - 1)) &
                                                     (modelo.VDem.por.pais$year < (data.fim + 1))), ] 

# insere column id pelo código uniforme de pais com dois digitos
colnames(modelo.VDem.por.pais.data)[colnames(modelo.VDem.por.pais.data) == 'country_id'] = 'cod_pais'

modelo.VDem.por.pais.data$cod_pais = as.character(modelo.VDem.por.pais.data$cod_pais)

for (k in 1:nrow(modelo.VDem.por.pais.data))
{
  if (modelo.VDem.por.pais.data$country_text_id  [k] ==     "ARG" ) 
  { modelo.VDem.por.pais.data$cod_pais  [k]  = "AR"}
  
  if (modelo.VDem.por.pais.data$country_text_id  [k] ==     "BOL" ) 
  { modelo.VDem.por.pais.data$cod_pais  [k]  = "BO"}
  
  if (modelo.VDem.por.pais.data$country_text_id  [k] ==     "BRA" ) 
  { modelo.VDem.por.pais.data$cod_pais  [k]  = "BR"}
  
  if (modelo.VDem.por.pais.data$country_text_id  [k] ==     "CHL" ) 
  { modelo.VDem.por.pais.data$cod_pais  [k]  = "CL"}
  
  if (modelo.VDem.por.pais.data$country_text_id  [k] ==     "COL" ) 
  { modelo.VDem.por.pais.data$cod_pais  [k]  = "CO"}
  
  if (modelo.VDem.por.pais.data$country_text_id  [k] ==     "CRI" ) 
  { modelo.VDem.por.pais.data$cod_pais  [k]  = "CR"}
  
  if (modelo.VDem.por.pais.data$country_text_id  [k] ==     "DOM" ) 
  { modelo.VDem.por.pais.data$cod_pais  [k]  = "DR"}
  
  if (modelo.VDem.por.pais.data$country_text_id  [k] ==     "SLV" ) 
  { modelo.VDem.por.pais.data$cod_pais  [k]  = "SV"}
  
  if (modelo.VDem.por.pais.data$country_text_id  [k] ==     "GTM" ) 
  { modelo.VDem.por.pais.data$cod_pais  [k]  = "GT"}
  
  if (modelo.VDem.por.pais.data$country_text_id  [k] ==     "HND" ) 
  { modelo.VDem.por.pais.data$cod_pais  [k]  = "HN"}
  
  if (modelo.VDem.por.pais.data$country_text_id   [k]  ==  "MEX" ) 
  { modelo.VDem.por.pais.data$cod_pais  [k]   = "MX"}
  
  if (modelo.VDem.por.pais.data$country_text_id  [k] ==  "NIC" ) 
  { modelo.VDem.por.pais.data$cod_pais  [k]  = "NI"}
  
  if (modelo.VDem.por.pais.data$country_text_id  [k] == "PAN" ) 
  { modelo.VDem.por.pais.data$cod_pais  [k]  = "PA"}
  
  if (modelo.VDem.por.pais.data$country_text_id  [k] ==   "PRY" ) 
  { modelo.VDem.por.pais.data$cod_pais  [k]  = "PY"}
  
  if (modelo.VDem.por.pais.data$country_text_id  [k] == "PER" ) 
  { modelo.VDem.por.pais.data$cod_pais  [k]  = "PE"}
  
  if (modelo.VDem.por.pais.data$country_text_id  [k] ==     "URY" ) 
  { modelo.VDem.por.pais.data$cod_pais  [k]  = "UY"}
  
  if (modelo.VDem.por.pais.data$country_text_id  [k] ==     "VEN" ) 
  { modelo.VDem.por.pais.data$cod_pais  [k]  = "VE"}
  
}
############################################################################################
# recupera dados polarização
############################################################################################
# 

polariz_raw <- modelo.VDem.por.pais.data [c('cod_pais', 'year', 'v2cacamps')]

polariz_subtotals <- polariz_raw %>% 
  group_by(year) %>%
  summarize (Subtotal = mean (v2cacamps))

polariz.results <- list(Numerical.values = polariz_raw, 
                        Yearly.average = polariz_subtotals)

write_xlsx(
  polariz.results,
  path = "polarization.raw.data.xlsx",
  col_names = TRUE,
  #  format_headers = TRUE,
  # use_zip64 = TRUE
)

